package com.maserb.monitor.service.schoolStudent.impl;

import com.maserb.monitor.entity.JwOrgEntity;
import com.maserb.monitor.entity.SysCode;
import com.maserb.monitor.entity.UserEntity;
import com.maserb.monitor.entity.schoolConduct.SchoolConductItemEntity;
import com.maserb.monitor.entity.schoolConduct.StudentConductRecordEntity;
import com.maserb.monitor.entity.schoolStudent.SchoolStudentEntity;
import com.maserb.monitor.entity.schoolStudent.StudentAchieveEntity;
import com.maserb.monitor.entity.schoolStudent.StudentScoreEntity;
import com.maserb.monitor.model.StudentAchieveModel;
import com.maserb.monitor.model.StudentAchieveScoreModel;
import com.maserb.monitor.repository.schoolStudent.StudentAchieveRepository;
import com.maserb.monitor.service.author_manage.UserService;
import com.maserb.monitor.service.base.IToolService;
import com.maserb.monitor.service.base.impl.JpaSpecificationServiceImpl;
import com.maserb.monitor.service.jwEducation.JwOrgService;
import com.maserb.monitor.service.schoolStudent.SchoolStudentService;
import com.maserb.monitor.service.schoolStudent.StudentAchieveService;
import com.maserb.monitor.service.schoolStudent.StudentScoreService;
import com.maserb.monitor.service.sysCode.SysCodeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.thymeleaf.util.StringUtils;

import javax.persistence.criteria.*;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

@Service
public class StudentAchieveServiceImpl extends JpaSpecificationServiceImpl<StudentAchieveRepository,
        StudentAchieveRepository, StudentAchieveEntity, String>
        implements StudentAchieveService {

    @Autowired
    SysCodeService codeService;

    @Autowired
    JwOrgService orgService;

    @Autowired
    IToolService toolService;

    @Autowired
    SchoolStudentService studentService;

    @Autowired
    StudentScoreService scoreService;

    @Autowired
    UserService userService;

    @Override
    public Page<StudentAchieveEntity> findAll(Pageable var1,String userId, String name,String studentId, final String term, final String clazzId) {
        UserEntity user = new UserEntity();
        List<JwOrgEntity> orgList = new ArrayList<JwOrgEntity>();
        List<String>orgIdList = new ArrayList<String>();
        if(!StringUtils.isEmptyOrWhitespace(userId)){
            user = userService.findOne(userId);
            if(null!=user &&!"".equals( user.getId())){
                orgList = orgService.findByUser(user);
                if(orgList.size()>0){
                    for(JwOrgEntity org:orgList){
                        orgIdList.add(org.getId());
                    }
                }else{
                    String orgId = user.getOrgId();
                    JwOrgEntity orgEntity = orgService.findOne(orgId);
                    if(null!=orgEntity && orgEntity.getTreeLevel()<1){

                    }else{
                        return null;
                    }
                }
            }
        }
        return this.findAll(getSpecification(orgIdList,userId,name,studentId,term,clazzId),var1);
    }

    private Specification<StudentAchieveEntity>getSpecification(List<String> orgIdList,String userId, String name,String studentId, final String term, final String clazzId){
        return new Specification<StudentAchieveEntity>() {
            @Override
            public Predicate toPredicate(Root<StudentAchieveEntity> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                ArrayList<Predicate> list = new ArrayList<Predicate>();
                Join<StudentAchieveEntity, SchoolStudentEntity> joinStudent = root.join("student", JoinType.LEFT);
                Path<String> pathJoinStudent = joinStudent.get("id");
                Path<String> pathJoinStudentName = joinStudent.get("name");
                Path<String> pathJoinStudentId = joinStudent.get("studentId");
                Path<String> pathJoinStudentOrgId = joinStudent.get("orgId");
                list.add(criteriaBuilder.and(criteriaBuilder.equal(pathJoinStudent, root.get("student"))));
                Path<String> pathTerm = root.get("term");
                Path<Date> pathCreateTime = root.get("createTime");
                if (null!=orgIdList && orgIdList.size()>0) {
                    Expression<String> exp = pathJoinStudentOrgId;
                    list.add(exp.in(orgIdList));
                }
                if (!StringUtils.isEmptyOrWhitespace(name)) {
                    list.add(criteriaBuilder.and(criteriaBuilder.like(pathJoinStudentName, "%"+name+"%")));
                }
                if (!StringUtils.isEmptyOrWhitespace(clazzId)) {
                    list.add(criteriaBuilder.and(criteriaBuilder.equal(pathJoinStudentOrgId, clazzId)));
                }
                if (!StringUtils.isEmptyOrWhitespace(studentId)) {
                    list.add(criteriaBuilder.and(criteriaBuilder.equal(pathJoinStudentId, studentId)));
                }
                if (!StringUtils.isEmptyOrWhitespace(term)) {
                    list.add(criteriaBuilder.and(criteriaBuilder.like(pathTerm, "%"+term+"%")));
                }
                return criteriaBuilder.and(list.toArray(new Predicate[list.size()]));
            }
        };
    }


    @Override
    public List<StudentAchieveEntity> findByStudentOrderByCreateTime(String startTime, String endTime,String studentId) {
        SchoolStudentEntity studentEntity = studentService.findOne(studentId);
        Date start =toolService.parseDateFromNormalDateFormat(startTime);
        Date end =toolService.parseDateFromNormalDateFormat(endTime);
        Calendar cal = Calendar.getInstance();
        cal.setTime(end);
        cal.add(Calendar.DATE,1);
        end =cal.getTime();
        if(null!= studentEntity){
            return this.repository.findByStudent(studentEntity,start,end);
        }
        return null;
    }

    @Override
    public List<StudentAchieveEntity> findByStudentByCreateTime(SchoolStudentEntity student) {
        if(null!= student){
            return this.repository.findByStudentByCreateTime(student);
        }
        return null;
    }

    @Override
    public Double[] findAchieveByClazz(String startTime, String endTime, String clazzId) {
        Date start =toolService.parseDateFromNormalDateFormat(startTime);
        Date end =toolService.parseDateFromNormalDateFormat(endTime);
        return this.repository.findAchieveByClazz(clazzId,start,end);
    }

    @Override
    public Double[] findAchieveByClazzAndCode(String startTime, String endTime, String clazzId, SysCode code) {
        Date start =toolService.parseDateFromNormalDateFormat(startTime);
        Date end =toolService.parseDateFromNormalDateFormat(endTime);
        return this.repository.findAchieveByClazzAndCode(clazzId,start,end,code);
    }

    @Override
    public void saveByFile(List<StudentAchieveScoreModel> list, String term) {
        for(StudentAchieveScoreModel model:list){
            if(null!=model && !StringUtils.isEmptyOrWhitespace(model.getStudentId())){
                SchoolStudentEntity student = studentService.findByStudentNo(model.getStudentId());
                if(null!=student && !StringUtils.isEmptyOrWhitespace(student.getId())){
                    StudentAchieveEntity achieveEntity = new StudentAchieveEntity();
                    achieveEntity.setStudent(student);
                    achieveEntity.setClazzId(student.getOrgId());
                    achieveEntity.setTerm(term);
                    achieveEntity.setCreateTime(new Date());
                    this.save(achieveEntity);
                    if(null!=model.getChineseScore()){
                        StudentScoreEntity scoreEntity1 = new StudentScoreEntity();
                        scoreEntity1.setAchieve(achieveEntity);
                        scoreEntity1.setCreateTime(new Date());
                        SysCode code = codeService.findByName("语文");
                        if(null!=code){
                            scoreEntity1.setSubject(code);
                        }
                        scoreEntity1.setScore(model.getChineseScore());
                        scoreService.save(scoreEntity1);
                        this.updateAchieve(achieveEntity);
                    }
                    if(null!=model.getMathScore()){
                        StudentScoreEntity scoreEntity1 = new StudentScoreEntity();
                        scoreEntity1.setAchieve(achieveEntity);
                        scoreEntity1.setCreateTime(new Date());
                        SysCode code = codeService.findByName("数学");
                        if(null!=code){
                            scoreEntity1.setSubject(code);
                        }
                        scoreEntity1.setScore(model.getMathScore());
                        scoreService.save(scoreEntity1);
                        this.updateAchieve(achieveEntity);
                    }
                    if(null!=model.getPoliticsScore()){
                        StudentScoreEntity scoreEntity1 = new StudentScoreEntity();
                        scoreEntity1.setAchieve(achieveEntity);
                        scoreEntity1.setCreateTime(new Date());
                        SysCode code = codeService.findByName("政治");
                        if(null!=code){
                            scoreEntity1.setSubject(code);
                        }
                        scoreEntity1.setScore(model.getPoliticsScore());
                        scoreService.save(scoreEntity1);
                        this.updateAchieve(achieveEntity);
                    }
                    if(null!=model.getEnglishScore()){
                        StudentScoreEntity scoreEntity3 = new StudentScoreEntity();
                        scoreEntity3.setAchieve(achieveEntity);
                        scoreEntity3.setCreateTime(new Date());
                        SysCode code = codeService.findByName("英语");
                        if(null!=code){
                            scoreEntity3.setSubject(code);
                        }
                        scoreEntity3.setScore(model.getEnglishScore());
                        scoreService.save(scoreEntity3);
                        this.updateAchieve(achieveEntity);
                    }

                    if(null!=model.getPhysicalScore()){
                        StudentScoreEntity scoreEntity4 = new StudentScoreEntity();
                        scoreEntity4.setAchieve(achieveEntity);
                        scoreEntity4.setCreateTime(new Date());
                        SysCode code = codeService.findByName("物理");
                        if(null!=code){
                            scoreEntity4.setSubject(code);
                        }
                        scoreEntity4.setScore(model.getPhysicalScore());
                        scoreService.save(scoreEntity4);
                        this.updateAchieve(achieveEntity);
                    }
                    if(null!=model.getChemistryScore()){
                        StudentScoreEntity scoreEntity5 = new StudentScoreEntity();
                        scoreEntity5.setAchieve(achieveEntity);
                        scoreEntity5.setCreateTime(new Date());
                        SysCode code = codeService.findByName("化学");
                        if(null!=code){
                            scoreEntity5.setSubject(code);
                        }
                        scoreEntity5.setScore(model.getChemistryScore());
                        scoreService.save(scoreEntity5);
                        this.updateAchieve(achieveEntity);
                    }
                    if(null!=model.getHistoryScore()){
                        StudentScoreEntity scoreEntity6 = new StudentScoreEntity();
                        scoreEntity6.setAchieve(achieveEntity);
                        scoreEntity6.setCreateTime(new Date());
                        SysCode code = codeService.findByName("历史");
                        if(null!=code){
                            scoreEntity6.setSubject(code);
                        }
                        scoreEntity6.setScore(model.getHistoryScore());
                        scoreService.save(scoreEntity6);
                        this.updateAchieve(achieveEntity);
                    }
                    if(null!=model.getGeographyScore()){
                        StudentScoreEntity scoreEntity7 = new StudentScoreEntity();
                        scoreEntity7.setAchieve(achieveEntity);
                        scoreEntity7.setCreateTime(new Date());
                        SysCode code = codeService.findByName("地理");
                        if(null!=code){
                            scoreEntity7.setSubject(code);
                        }
                        scoreEntity7.setScore(model.getGeographyScore());
                        scoreService.save(scoreEntity7);
                        this.updateAchieve(achieveEntity);
                    }
                    if(null!=model.getBiologicalScore()){
                        StudentScoreEntity scoreEntity8 = new StudentScoreEntity();
                        scoreEntity8.setAchieve(achieveEntity);
                        scoreEntity8.setCreateTime(new Date());
                        SysCode code = codeService.findByName("生物");
                        if(null!=code){
                            scoreEntity8.setSubject(code);
                        }
                        scoreEntity8.setScore(model.getBiologicalScore());
                        scoreService.save(scoreEntity8);
                        this.updateAchieve(achieveEntity);
                    }
                    if(null!=model.getMoralScore()){
                        StudentScoreEntity scoreEntity9 = new StudentScoreEntity();
                        scoreEntity9.setAchieve(achieveEntity);
                        scoreEntity9.setCreateTime(new Date());
                        SysCode code = codeService.findByName("思想品德");
                        if(null!=code){
                            scoreEntity9.setSubject(code);
                        }
                        scoreEntity9.setScore(model.getMoralScore());
                        scoreService.save(scoreEntity9);
                        this.updateAchieve(achieveEntity);
                    }
                    if(null!=model.getEducationScore()){
                        StudentScoreEntity scoreEntity10 = new StudentScoreEntity();
                        scoreEntity10.setAchieve(achieveEntity);
                        scoreEntity10.setCreateTime(new Date());
                        SysCode code = codeService.findByName("体育");
                        if(null!=code){
                            scoreEntity10.setSubject(code);
                        }
                        scoreEntity10.setScore(model.getEducationScore());
                        scoreService.save(scoreEntity10);
                        this.updateAchieve(achieveEntity);
                    }
                    if(null!=model.getInformationScore()){
                        StudentScoreEntity scoreEntity11 = new StudentScoreEntity();
                        scoreEntity11.setAchieve(achieveEntity);
                        scoreEntity11.setCreateTime(new Date());
                        SysCode code = codeService.findByName("信息技术");
                        if(null!=code){
                            scoreEntity11.setSubject(code);
                        }
                        scoreEntity11.setScore(model.getInformationScore());
                        scoreService.save(scoreEntity11);
                        this.updateAchieve(achieveEntity);
                    }
                    if(null!=model.getLaborScore()){
                        StudentScoreEntity scoreEntity12 = new StudentScoreEntity();
                        scoreEntity12.setAchieve(achieveEntity);
                        scoreEntity12.setCreateTime(new Date());
                        SysCode code = codeService.findByName("劳动技术");
                        if(null!=code){
                            scoreEntity12.setSubject(code);
                        }
                        scoreEntity12.setScore(model.getLaborScore());
                        scoreService.save(scoreEntity12);
                        this.updateAchieve(achieveEntity);
                    }
                    if(null!=model.getComprehensiveScore()){
                        StudentScoreEntity scoreEntity13 = new StudentScoreEntity();
                        scoreEntity13.setAchieve(achieveEntity);
                        scoreEntity13.setCreateTime(new Date());
                        SysCode code = codeService.findByName("综合实践");
                        if(null!=code){
                            scoreEntity13.setSubject(code);
                        }
                        scoreEntity13.setScore(model.getComprehensiveScore());
                        scoreService.save(scoreEntity13);
                        this.updateAchieve(achieveEntity);
                    }
                    if(null!=model.getMusicScore()){
                        StudentScoreEntity scoreEntity14 = new StudentScoreEntity();
                        scoreEntity14.setAchieve(achieveEntity);
                        scoreEntity14.setCreateTime(new Date());
                        SysCode code = codeService.findByName("音乐");
                        if(null!=code){
                            scoreEntity14.setSubject(code);
                        }
                        scoreEntity14.setScore(model.getMusicScore());
                        scoreService.save(scoreEntity14);
                        this.updateAchieve(achieveEntity);
                    }
                    if(null!=model.getArtScore()){
                        StudentScoreEntity scoreEntity15 = new StudentScoreEntity();
                        scoreEntity15.setAchieve(achieveEntity);
                        scoreEntity15.setCreateTime(new Date());
                        SysCode code = codeService.findByName("美术");
                        if(null!=code){
                            scoreEntity15.setSubject(code);
                        }
                        scoreEntity15.setScore(model.getArtScore());
                        scoreService.save(scoreEntity15);
                        this.updateAchieve(achieveEntity);
                    }
                    if(null!=model.getTotalScore()){
                        achieveEntity.setTotalScore(model.getTotalScore());
                        repository.save(achieveEntity);
                    }
                    if(null!=model.getClazzRank()){
                        achieveEntity.setClazzRank(model.getClazzRank());
                        repository.save(achieveEntity);
                    }
                    if(null!=model.getCityRank()){
                        achieveEntity.setCityRank(model.getCityRank());
                        repository.save(achieveEntity);
                    }
                }
            }
        }
    }

    @Override
    public List<StudentAchieveEntity> findAchieveByClazzOrderByTotalScoreDesc(String clazzId, String term) {
        return this.repository.findAchieveByClazzOrderByTotalScoreDesc(clazzId,term);
    }

    public void updateAchieve(StudentAchieveEntity achieveEntity){
        List<StudentScoreEntity>scoreEntities = scoreService.findByAchieve(achieveEntity);
        if(scoreEntities.size()>0){
            Double totalScore = 0d;
            Double avgScore = 0d;
            Integer subjectCount = scoreEntities.size();
            for(StudentScoreEntity scoreEntity : scoreEntities){
                totalScore += scoreEntity.getScore();
            }
            avgScore = (double)Math.round((totalScore/subjectCount)*10)/10;
            achieveEntity.setTotalScore(totalScore);
            achieveEntity.setAvgScore(avgScore);
            achieveEntity.setSubjectCount(subjectCount);
            this.save(achieveEntity);
        }
    }

    @Override
    public void delete(String var1) {
        StudentAchieveEntity entity = this.findOne(var1);
        List<StudentScoreEntity> scoreEntityList = scoreService.findByAchieve(entity);
        scoreService.delete(scoreEntityList);
        super.delete(var1);
    }

}